/* eslint-disable no-unneeded-ternary */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/* eslint-disable @typescript-eslint/no-shadow */
import type { ConnectState } from '@/models/connect';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import React, { useRef, useState } from 'react';
import type { CurrentUser, Dispatch } from 'umi';
import { connect } from 'umi';
import { getCabinet,cabinetDataToCsvApi,unbindSellerDevice } from '@/services/device';
import { Tag, Button, message, Spin, Popconfirm } from 'antd';
import type { CabinetExportParams, GetCabinetParamsType } from '@/services/device';
import SellerSelectModal from '@/components/SellerSelectModal/SellerSelectModal';
import  Manage  from './components/manage'
import { AlignCenterOutlined } from '@ant-design/icons';
import UseRate from './components/UseRate';

interface CabinetProps {
  dispatch: Dispatch;
  userState?: CurrentUser;
}

// addr: "港北区迎宾华府小香葱"
// cabinet_id: "YD06191200008"
// heartbeat_time: "2020-11-12 13:05:07"
// model: "6"
// name: "小香葱（迎宾华府店）"
// sid: 4806
// type: "1"
interface CabinetItemInfo {
  addr: string;
  cabinet_id: string;
  heartbeat_time: string;
  model: string;
  sname: string;
  sid: string; // 商户编号
  type: string; // 设备类型
  binding: boolean; // 是否绑定商户
  online_status: boolean; // 在线状态
}

const CabinetList: React.FC<CabinetProps> = (props) => {
  const { userState } = props;
  const [page, setPage] = useState(1); // 设置页数
  const [limit, setLimit] = useState(20); // 设置数据读取数
  const [total, setTotal] = useState(0); // 设置数据总数
  const [deviceId, setDeviceId] = useState(''); // 设置过滤机柜编号
  const [sid, setSid] = useState(''); // 设置商户id
  const [name, setName] = useState(''); // 设置过滤商户名称
  const [status, setStatus] = useState(0); // 设置过滤商户名称
  const [binding, setBinding] = useState(0); // 查看是否铺货
  const [aid, setAid] = useState(''); // 查看代理id
  const [aname, setAname] = useState(''); // 设置代理名称
  const [num, setNum] = useState(0); // 设置数量
  const [numOperation, setNumOperation] = useState(1); // 设置操作

  const [loading, setLoading] = useState(false); // 是否加载中
  const [infoShow, setInfoShow] = useState(false); // 使用率统计
  const [selectDevice, setSelectDevice] = useState<number | string>(); // 选择的机柜

  const ref = useRef<ActionType>();
       
  // 表格配置
  let columns: ProColumns<CabinetItemInfo>[] = [
    // {
    //   title: '操作',
    //   key: 'option',
    //   valueType: 'option',
    //   fixed: 'left',
    //   render: (_, row) => {
    //     return row.binding === true ? (
    //       <Popconfirm
    //         title="确定要解绑吗?"
    //         onConfirm={() => unbindSellerDevice(row.cabinet_id)}
    //         okText="确定"
    //         cancelText="取消"
    //       >
    //         <a>解绑(商户)</a>
    //       </Popconfirm>
    //     ) : (
    //       <SellerSelectModal
    //         deviceId={row.cabinet_id}
    //         userState={userState}
    //         confirmFn={bindSellerDevice}
    //       ></SellerSelectModal>
    //     );
    //   },
    // },
    {
      title: '机柜编号',
      dataIndex: 'cabinet_id',
      valueType: 'textarea',
      copyable: true,
    },
    {
      title: '商户Id',
      dataIndex: 'sid',
    },
    {
      title: '商户名称',
      dataIndex: 'sname',
      copyable: true,
    },
    {
      title: '代理Id',
      dataIndex: 'aid',
      hideInTable: true,
    },
    {
      title: '代理名称',
      dataIndex: 'aname',
      hideInTable: true,
    },
    {
      title: '详细地址',
      dataIndex: 'addr',
      search: false,
    },
    {
      title: '在线状态',
      dataIndex: 'online_status',
      search: false,
      render: (_, row) => {
        if (row.online_status === true) {
          return (
            <Tag color="green" key={row.cabinet_id}>
              在线
            </Tag>
          );
        }
        return (
          <Tag color="red" key={row.cabinet_id}>
            离线
          </Tag>
        );
      },
    },
    {
      title: '在线状态',
      dataIndex: 'online_status_search',
      hideInTable: true,
      valueEnum: {
        0: { text: '全部' },
        1: { text: '在线' },
        2: { text: '离线' },
      },
    },
    {
      title: '最后心跳时间',
      dataIndex: 'heartbeat_time',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '设备型号',
      search: false,
      dataIndex: 'model',
    },
    {
      title: '充电宝数量',
      dataIndex: 'power_bank_num_operation',
      hideInTable: true,
      valueEnum: {
        1: { text: '等于' },
        2: { text: '大于' },
        3: { text: '小于' },
      },
    },
    {
      title: '',
      dataIndex: 'power_bank_num',
      hideInTable: true,
      
    },
    {
      title: '是否铺货',
      dataIndex: 'binding',
      valueEnum: {
        1: { text: '全部' },
        true: { text: '已铺货', status: 'Processing' },
        false: { text: '未铺货', status: 'Error' },
      },
    },
    {
      title: '计费说明',
      dataIndex: 'charge_rule',
      search: false,
    },
    
  ];
  // 判断代理等级是不是大于店铺代理
  if (
    props.userState &&
    props.userState.type &&
    (props.userState.type === 5 || props.userState.type < 5)
  ) {
    columns = columns.concat([
      {
        title: '店铺管理ID',
        search: false,
        dataIndex: 'said',
        copyable: true,
      },
      {
        title: '店铺管理名称',
        search: false,
        dataIndex: 'saname',
      },
      {
        title: '店铺管理分润',
        search: false,
        dataIndex: 'sbrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于业务代理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 1
  ) {
    columns = columns.concat([
      {
        title: '业务代理ID',
        search: false,
        dataIndex: 'baid',
        copyable: true,
      },
      {
        title: '业务代理名称',
        search: false,
        dataIndex: 'baname',
      },
      {
        title: '业务代理分润',
        search: false,
        dataIndex: 'bbrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于区域经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 2
  ) {
    columns = columns.concat([
      {
        title: '区域经理ID',
        search: false,
        dataIndex: 'aaid',
        copyable: true,
      },
      {
        title: '区域经理名称',
        search: false,
        dataIndex: 'aaname',
      },
      {
        title: '区域经理收益',
        search: false,
        dataIndex: 'abrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于市级经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 3
  ) {
    columns = columns.concat([
      {
        title: '市级代理ID',
        search: false,
        dataIndex: 'caid',
        copyable: true,
      },
      {
        title: '市级代理名称',
        search: false,
        dataIndex: 'caname',
      },
      {
        title: '市级代理收益',
        search: false,
        dataIndex: 'cbrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于省级经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type === 4
  ) {
    columns = columns.concat([
      {
        title: '省级代理ID',
        search: false,
        dataIndex: 'paid',
        copyable: true,
      },
      {
        title: '省级代理名称',
        search: false,
        dataIndex: 'paname',
      },
      {
        title: '省级代理分润',
        search: false,
        dataIndex: 'pbrokerage',
      },
    ]);
  }

  // 固定操作栏
  columns.push({
    title: '操作',
    key: 'option',
    fixed: 'right',
    valueType: 'option',
    render: (_, row) => [
      // 使用率统计
      <Button
        key={row.cabinet_id}
        type="primary"
        onClick={() => {
          setSelectDevice(row.cabinet_id);
          setInfoShow(true);
        }}
      >
        <AlignCenterOutlined />
        设备详情
      </Button>,
    ],
  });

  return (
    <PageContainer>
      <Spin spinning={loading} tip="导出中...">
      <ProTable
        headerTitle="机柜管理"
        
        onReset={() => {
          setPage(1);
        }}
        rowKey={columns => columns.cabinet_id}
        scroll={{ x: 'max-content' }}
        search={{
          defaultCollapsed: false,
        }}
        request={async () => {
          const data: GetCabinetParamsType = {
            uId: userState?.id!,
            userType: userState?.user_type!,
            token: userState?.token!,
            page,
            limit,
            device_id: deviceId,
            sname: name,
            aid,
            sid,
            aname,
            binding,
            power_bank_num: Number(num),
            power_bank_num_operation: Number(numOperation),
            status
          };
          return getCabinet(data);
        }}
        postData={(res) => {
          setTotal((res as any).num);
          return (res as any).data;
        }}
        beforeSearchSubmit={(params: any) => {
            
            // 查找机柜
            if (params.cabinet_id) {
              setDeviceId(params.cabinet_id);
            } else {
              setDeviceId('');
            }
            // 查找商户id
            if (params.sid) {
              setSid(params.sid);
            } else {
              setSid('');
            }
            // 查找商户
            if (params.name) {
              setName(params.name);
            } else {
              setName('');
            }
            // 查看是否铺货
            if (params.binding === 'true') {
              setBinding(1);
            } else if (params.binding === 'false') {
              setBinding(2);
            } else {
              setBinding(0);
            }
            // 设置代理id
            if (params.aid) {
              setAid(params.aid);
            } else {
              setAid('');
            }
            // 设置代理名称
            if (params.aname) {
              setAname(params.aname);
            } else {
              setAname('');
            }
            // 设置充电宝数量
            if (params.power_bank_num) {
              setNum(params.power_bank_num);
            } else {
              setNum(0);
            }

            // 设置充电宝数量 
            if (params.power_bank_num_operation) {
              setNumOperation(params.power_bank_num_operation);
            } else {
              setNumOperation(1);
              
              
          }
              // 设置状态
              if (params.online_status_search) {
                setStatus(Number(params.online_status_search));
              } else {
                setStatus(0);
              }
              return params;
          }
          }
        // 工具栏
          toolBarRender={() => [
          <Manage
              title="批量操作(商户)"
              type={1}
              key="manage"
              updateData={() => ref.current?.reload()}
            ></Manage>,
            <Manage
              title="批量操作(代理)"
              type={2}
              key="manage"
              updateData={() => ref.current?.reload()}
            ></Manage>,
          <Button
            onClick={async () => {
              try {
                const data: CabinetExportParams = {
                    uId: Number(userState?.id!),
                    userType: Number(userState?.user_type!),
                    token: userState?.token!,
                    device_id: deviceId,
                    sid: sid ? Number(sid) : null,
                    sname: name,
                    aid: aid ? Number(aid) : null,
                    aname,
                    binding,
                  status,
                    power_bank_num: Number(num),
            power_bank_num_operation: Number(numOperation),
                  };
                  setLoading(true);
                  const res = await cabinetDataToCsvApi(data);
                  if (res.code === 0) {
                    const newUrl = await (await fetch(res.data)).arrayBuffer(); // 将返回数据转成buff对象
                    const nowTime = new Date().toLocaleString();
                    const fileName = `${nowTime}机柜列表.csv`;
                    const myBlob = new Blob([newUrl], { type: 'text/csv,charset=UTF-8' });
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(myBlob);
                    link.download = fileName;
                    link.click();
                    link.remove();
                    URL.revokeObjectURL(link.href);
                    setLoading(false);
                    message.success('导出成功');
                  } else {
                    message.error(res.msg);
                  }
                } catch (error) {
                  console.log(error);
                }
              }}
            >
              导出
            </Button>,
          ]}
          pagination={{
            pageSize: limit,
            total,
            onChange: (page) => {
              setPage(page);
            },
            onShowSizeChange: (_, size) => {
              setLimit(size);
            },
          }}
          columns={columns}
        ></ProTable>
      </Spin>
      <UseRate
        visible={infoShow}
        onCancel={() => {
          setInfoShow(false);
          setSelectDevice('');
        }}
        uId={userState?.id!}
        userType={userState?.user_type!}
        token={userState?.token!}
        cabinet_id={selectDevice ?? ''}
      ></UseRate>
    </PageContainer>
  );
};

export default connect(({ user }: ConnectState) => ({ userState: user.currentUser }))(CabinetList);
